<template>
    <div class="add-role">
        <Form
            ref="addForm"
            :model="form"
            :rules="diyData.rules"
            :label-width="100"
        >
            <div class="tag-title">{{query.id ? '编辑' :'添加'}}角色</div>
            <FormItem label="角色名称" prop="name">
                <Input clearable 
                    v-model="form.name"
                    placeholder="请输入角色名称"
                    style="width: 440px"
                ></Input>
            </FormItem>

            <FormItem label="角色标识" prop="slug">
                <Input clearable 
                    v-model="form.slug"
                    placeholder="请输入角色标识"
                    type="text"
                    style="width: 440px"
                ></Input>
            </FormItem>

            <FormItem label="菜单列表" prop="menus">
                <Tree :data="apiData.apiAccessList" @on-check-change="checkChange" ref="tree" show-checkbox></Tree>
            </FormItem>

        </Form>
        <Button
            type="primary"
            style="width: 90px; margin-right: 20px"
            @click="submit"
        >
            保存
        </Button>
        <Button style="width: 90px" @click="$router.go(-1)">
            取消
        </Button>
    </div>
</template>

<script>
import {apiRoleDetail, apiRoleUpdate, apiRoleAdd, apiMenuList} from '@/api/admin';

export default {
    name: 'add-role',
    data() {
        return {
            query: {},
            search: {},
            diyDom: {},
            // 表单数据
            form: {
                name: '',
                slug: '',
                menus: [],
            },
            diyData: {
                rules: {
                    name: [{required: true, message: '角色名称不能为空', trigger: 'blur'}],
                    slug: [{required: true, message: '角色标识不能为空', trigger: 'blur'}],
                },
                menuArr: [], // 反查询菜单
            },
            apiData: {
                apiAccessList: [],
            }
        };
    },
    methods: {
        // 获取角色详情
        getDetail() {
            apiRoleDetail(this.query.id).then(res => {
                const {name, slug, menus} = res;
                this.form.name = name;
                this.form.slug = slug;
                this.selectAuth(menus,this.apiData.apiAccessList)
            });
            this.$forceUpdate()
        },

        // 迭代选择的菜单
        selectAuth(menus,arr){
            menus.forEach(item => {
                arr.forEach((citem,cindex) => {
                    if(citem.id == item) {
                        this.$set(arr[cindex],'checked',true)
                    }
                    if(citem.children && citem.children.length > 0) {
                        // 如果存在子菜单，把父菜单选择为空，不然会全部选择上，在提交的时候，用数组去重
                        this.$set(arr[cindex],'checked',false)
                       this.selectAuth(menus,citem.children)
                    }
                })
            })
        },
        checkChange(e) {
            console.log(e);
        },

        // 获取菜单
        getTreeList() {
            apiMenuList().then(res => {
                this.dealAccessData(res);
            });
        },
        // 处理数据
        dealAccessData(data) {
            let map = {};
            data.forEach(item => {
                map[item.id] = item;
            });
            data.forEach(item => {
                let parent = map[item.parent];  //判断item的pid是否是否存在map中
                if (parent) {  //如果存在则表示item不是最顶层的数据
                    (parent.children || (parent.children = [])).push(item);
                } else {
                    this.apiData.apiAccessList.push(item);  // 如果不存在 则是顶层数据
                }
            });
            // 请求详情
            this.query.id && this.getDetail();
        },
        // 迭代菜单,寻找父级菜单
        getMenuParentIid(form, menu) {
            this.diyData.menuArr = [...new Set(this.diyData.menuArr)];
            form.forEach(item => {
                menu.forEach(citem => {
                    if (item == citem.id && citem.parent_id != 0) {
                        this.diyData.menuArr.push(citem.parent_id);
                    } else if (citem.children && citem.children.length > 0) {
                        this.getMenuParentIid(form, citem.children);
                    }
                });
            });
        },

        submit() {
            this.form.menus = []
            this.$refs.tree.getCheckedNodes().forEach(item => {
                if(item.parent_id && item.parent_id !=0) {
                    this.form.menus.push(item.parent_id);
                }
                this.form.menus.push(item.id);
            });
            // 数组去重
            this.getMenuParentIid(this.form.menus, this.apiData.apiAccessList);
            // 数组去重
            this.form.menus = [...new Set([...this.form.menus, ...this.diyData.menuArr])].sort();

            this.$refs['addForm'].validate((valid) => {
                if (valid) {
                    const opt = {...this.form};
                    if (this.query.id) {
                        apiRoleUpdate(this.query.id, opt).then(
                            (res) => {
                                this.$Message.success('编辑成功');
                                this.$router.push({name: 'role-manage'});
                            }
                        );
                    } else {
                        apiRoleAdd(opt).then(
                            (res) => {
                                this.$Message.success('新增成功');
                                this.$router.push({name: 'role-manage'});
                            }
                        );
                    }
                }
            });
        }
    },
    mounted() {
        this.query = this.$route.query;
        // this.getTreeList();
    }
};
</script>

<style scoped lang="less">
.add-role {
    border: 1px solid #ededed;
    margin: 0 20px;
    padding: 26px 20px;


    .title {
        border-left: 5px solid #2d8cf0;
        padding: 0 0 0 10px;
        margin: 0 20px 20px;
        font-weight: bold;
    }

    .ivu-tree {
        margin: 0;
    }


    .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.6);
        text-align: center;
    }

    .look-img:hover .demo-upload-list-cover {
        display: block;
    }

    .demo-upload-list-cover i {
        line-height: 98px;
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }

    .demo-spin-icon-load {
        animation: ani-demo-spin 1s linear infinite;
    }


}
</style>
